#!/usr/bin/env python

import os
import app
import model
import dialog
import serial
import thread
import component

class Main(component.Presenter):
    '''Main class
    
    @author Julot <andy.julot@gmail.com>
    @since Saturday, January 14, 2012. 09:07 AM'''
    
    def __init__(self, view, interactor):
        super(Main, self).__init__(view, interactor)
        if not os.path.lexists('data'): os.mkdir('data')
        self.readColumnWidth()
    
    _stopped = True
    
    def onClose(self):
        if self._stopped:
            self.writeColumnWidth()
            super(Main, self).onClose()
            self.view.Destroy()
    
    def readColumnWidth(self):
        config = app.Config()
        for col in range(self.view.data.GetColumnCount() - 1):
            key = '%s/Col%s' % (self.view.Name, col)
            value = config.ReadInt(key, -1)
            if value != -1:
                self.view.data.SetColumnWidth(col, value)
    
    def writeColumnWidth(self):
        config = app.Config()
        for col in range(self.view.data.GetColumnCount() - 1):
            key = '%s/Col%s' % (self.view.Name, col)
            config.WriteInt(key, self.view.data.GetColumnWidth(col))
        
    def close(self):
        if self._stopped:
            self.view.Close()
    
    _about = None
    
    def showAbout(self):
        if not self._about: self._about = dialog.About(self.view)
        self._about.Center()
        self._about.Show()
    
    _gps = None
    
    def loadGps(self):
        if not self._gps:
            config = app.Config()
            port = config.Read('GPS/Port', 'COM1')
            baudrate = config.ReadInt('GPS/Baudrate', 4800)
            try:
                self._gps = serial.Serial(port, baudrate)
            except:
                self._gps = None
        return self._gps
        
    def start(self):
        gps = self.loadGps()
        if not gps:
            self.view.messageDialog('GPS is missing.', 'Error')
            return
        
        self._stopped = False
        self.view.start()
        thread.start_new_thread(self.readGps, ())
    
    def readGps(self):
        gps = self.loadGps()
        garmin = model.Garmin()
        while not self._stopped:
            line = gps.readline()
            if not line: continue
            
            garmin.add(line)
            if not garmin.completed: continue
            
            self.view.data.add(garmin)
            garmin.save()
            garmin = model.Garmin()
    
    def stop(self):
        self.view.stop()
        self._stopped = True
    